package cn.ljlao.mall.product.goods.service.impl;

import cn.ljlao.common.utils.PageUtils;
import cn.ljlao.common.utils.Query;
import cn.ljlao.mall.product.goods.constant.RedisKeyConstant;
import cn.ljlao.mall.product.goods.service.CategoryBrandRelationService;
import cn.ljlao.mall.product.goods.util.RedisUtil;
import cn.ljlao.mall.product.goods.vo.Catalog2Vo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.ljlao.mall.product.goods.dao.CategoryDao;
import cn.ljlao.mall.product.goods.entity.CategoryEntity;
import cn.ljlao.mall.product.goods.service.CategoryService;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listTree() {
        List<CategoryEntity> list = baseMapper.selectList(null);
        //找到所有的一级分类
        List<CategoryEntity> level1Menus = list.stream()
                .filter(item -> item.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, list));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return level1Menus;
    }

    /**
     * 组织方法
     * @param root 当前元素
     * @param all 全部元素
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrens = all.stream()
                .filter(item -> {
                    //过滤出 父id  是当前节点id 的元素
                    return item.getParentCid().equals(root.getCatId());
                })
                .map(item -> {
                    //给当前节点 设置他的下级分组 递归
                    item.setChildren(getChildrens(item, all));
                    return item;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());

        return childrens;
    }


    @Override
    public List<CategoryEntity> listTree2() {
        List<CategoryEntity> list = baseMapper.selectList(null);
        List<CategoryEntity> collect = list.stream()
                //过滤出一级菜单
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                     categoryEntity.setChildren(getChildrens(categoryEntity, list));
                    return categoryEntity;
                }).sorted((o1,o2)->{
                    return (o2.getSort()==null?0:o2.getSort()) -  (o1.getSort()==null?0:o1.getSort());
                })
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public Long[] getCatePath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        paths = getCategorysPath(catelogId,paths);
        //翻转 [225,20,2]  转成 [2,20,225]
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    @Override
    public void saveDetial(CategoryEntity category) {
        this.save(category);


    }

    /**
     * // 删除某个分区下的缓存数据，也就是清除模式
     *        @CacheEvict(value = "category",allEntries = true)
     * 	// 如果希望修改完数据，再往缓存里放一份，也就是双写模式，可以使用这个注解
     *    @CachePut
     *
     */

    // 删除多个分区的缓存数据
    @Caching(evict = {
            @CacheEvict(value = "category", key = "'level1Categories'"),
            @CacheEvict(value = "category", key = "'categoryJson'"),
    })
    @Override
    public void updateByDetail(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())){
            categoryBrandRelationService.updateByCategory(category.getCatId(),category.getName());
        }
    }

    /**
     * 查询所有的一级分类
     * @return
     */
    @Override
    @Cacheable(value = {"category"}, key = "'level1Categories'")
    public List<CategoryEntity> getLevel1Categorys() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    /**
     * 查询所有的二三级分类  分布式锁操作
     * @return
     */

    public Map<String, List<Catalog2Vo>> getCatalogJson2() {

        Object o = redisUtil.get(RedisKeyConstant.PRODUCT_MENU_THREE_LEVEL);
        Map<String, List<Catalog2Vo>> map = null;
        if (o!=null){
            log.info("redis 找到缓存 走缓存");
            //redisUtil.setIfAbsent()
            map = JSON.parseObject(o.toString(), new TypeReference<Map<String, List<Catalog2Vo>>>(){});
        }


        String s = UUID.randomUUID().toString();
        if (o == null){
            log.info("redis 没有找到缓存 走数据库");
            log.info("redis 上锁");
            // 上锁操作 锁key value 超时时间 超时单位
            Boolean b = redisUtil.setIfAbsent(RedisKeyConstant.REDIS_LOCK_KEY, s, 300, TimeUnit.SECONDS);
            if (b){ //上锁成功 走数据库 设置缓存
                log.info("redis 上锁成功 查询数据库");
                Map<String, List<Catalog2Vo>> stringListMap = getStringListMap();
                //将值 set进redis
                redisUtil.set(RedisKeyConstant.PRODUCT_MENU_THREE_LEVEL,stringListMap);
                //redis 解锁 使用lua 脚本  ,  脚本, key ,value
                redisTemplate.execute(RedisScript.of(RedisKeyConstant.REDIS_DEL_KEY_SCRIPT),Arrays.asList(RedisKeyConstant.REDIS_LOCK_KEY),s);
            }else {
                log.info("redis 上锁失败自旋 等待锁释放");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCatalogJson();
            }



        }

        return map;
    }

    /**
     * 查询全部分类
     * 使用SpringCache缓存版本
     * 只需要操作数据库，不需要关心缓存，一个注解就够了
     * @return
     */
    @Cacheable(value = {"category"}, key = "'categoryJson'")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //查询出所有分类
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //先查出所有一级分类
        List<CategoryEntity> level1Categorys = getCategorys(selectList, 0L);

        //拼接结果集
        Map<String, List<Catalog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //获取所有的2级集合
            List<CategoryEntity> level2Categorys = getCategorys(selectList, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (level2Categorys != null) {
                catalog2Vos = level2Categorys.stream().map(l2 -> {
                    // 封装catlog2Vo
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), l2.getCatId().toString(), l2.getName(), null);
                    //根据每个二级分类 查找三级分类集合
                    List<CategoryEntity> level3Categorys = getCategorys(selectList, l2.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (level3Categorys != null) {
                        //封装三级分类数据
                        catalog3Vos = level3Categorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo();
                            catalog3Vo.setCatalog2Id(l2.getCatId().toString());
                            catalog3Vo.setId(l3.getCatId().toString());
                            catalog3Vo.setName(l3.getName());
                            return catalog3Vo;

                        }).collect(Collectors.toList());
                    }
                    //将三级 集合 set 进 二级 vo
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    //返回
                    return catalog2Vo;

                }).collect(Collectors.toList()); // 转成list
            }
            // 将 2级volist 返回
            return catalog2Vos;

        }));


        return map;
    }




    /**
     * 查询所有的二三级分类
     * @return
     */
    private Map<String, List<Catalog2Vo>> getStringListMap() {
        //查询出所有分类
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //先查出所有一级分类
        List<CategoryEntity> level1Categorys = getCategorys(selectList, 0L);

        //拼接结果集
        Map<String, List<Catalog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //获取所有的2级集合
            List<CategoryEntity> level2Categorys = getCategorys(selectList, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if (level2Categorys != null) {
                catalog2Vos = level2Categorys.stream().map(l2 -> {
                    // 封装catlog2Vo
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), l2.getCatId().toString(), l2.getName(), null);
                    //根据每个二级分类 查找三级分类集合
                    List<CategoryEntity> level3Categorys = getCategorys(selectList, l2.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (level3Categorys != null) {
                        //封装三级分类数据
                        catalog3Vos = level3Categorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo();
                            catalog3Vo.setCatalog2Id(l2.getCatId().toString());
                            catalog3Vo.setId(l3.getCatId().toString());
                            catalog3Vo.setName(l3.getName());
                            return catalog3Vo;

                        }).collect(Collectors.toList());
                    }
                    //将三级 集合 set 进 二级 vo
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    //返回
                    return catalog2Vo;

                }).collect(Collectors.toList()); // 转成list
            }
            // 将 2级volist 返回
            return catalog2Vos;

        }));


        return map;
    }

    /**
     * 根据传进分类筛选出对应级别
     *
     * @param list
     * @param parent_cid
     * @return
     */
    public List<CategoryEntity> getCategorys(List<CategoryEntity> list, Long parent_cid) {
        List<CategoryEntity> collect = list.stream().filter(l -> parent_cid.equals(l.getParentCid())).collect(Collectors.toList());
        return collect;
    }

    /**
     * 递归获取层级
     * @param catelogId 根节点
     * @param paths 路径
     * @return
     */
    private List<Long> getCategorysPath(Long catelogId, List<Long> paths) {
        //先添加
        paths.add(catelogId);
        //根据id查询
        CategoryEntity byId = getById(catelogId);
        //如果有父id 继续递归查
        if (byId.getParentCid()!=0){
            getCategorysPath(byId.getParentCid(),paths);
        }
        return paths;
    }


}